package org.jeecgframework.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.Highchart;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.CbsInspectionEvaluateServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyInspectionPlanServiceI;
import org.jeecgframework.web.service.ZyInspectionReportServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 巡检报告
 * @author onlineGenerator
 * @date 2016-04-12 15:05:26
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyInspectionReportController")
public class ZyInspectionReportController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyInspectionReportController.class);

	@Autowired
	private ZyInspectionReportServiceI zyInspectionReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService	zyCommonService;
	@Autowired
	private ZyInspectionPlanServiceI zyInspectionPlanService;
	@Autowired
	private CbsInspectionEvaluateServiceI cbsInspectionEvaluateServiceI;
	@Autowired
	private UserService userService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


//	/**
//	 * 巡检报告列表 页面跳转
//	 * 
//	 * @return
//	 */
//	@RequestMapping(params = "zyInspectionReport")
//	public ModelAndView zyInspectionReport(HttpServletRequest request) {
//		return new ModelAndView("com/zybk/zy_inspection_report/zyInspectionReportList");
//	}
//
//	/**
//	 * easyui AJAX请求数据
//	 * 
//	 * @param request
//	 * @param response
//	 * @param dataGrid
//	 * @param user
//	 */
//
//	@RequestMapping(params = "datagrid")
//	public void datagrid(ZyInspectionReportEntity zyInspectionReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
//		CriteriaQuery cq = new CriteriaQuery(ZyInspectionReportEntity.class, dataGrid);
//		//查询条件组装器
//		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyInspectionReport, request.getParameterMap());
//		try{
//		//自定义追加查询条件
//		}catch (Exception e) {
//			throw new BusinessException(e.getMessage());
//		}
//		cq.add();
//		this.zyInspectionReportService.getDataGridReturn(cq, true);
//		TagUtil.datagrid(response, dataGrid);
//	}
//
//	/**
//	 * 删除巡检报告
//	 * 
//	 * @return
//	 */
//	@RequestMapping(params = "doDel")
//	@ResponseBody
//	public AjaxJson doDel(ZyInspectionReportEntity zyInspectionReport, HttpServletRequest request) {
//		AjaxJson j = new AjaxJson();
//		zyInspectionReport = systemService.getEntity(ZyInspectionReportEntity.class, zyInspectionReport.getId());
//		message = "巡检报告删除成功";
//		try{
//			zyInspectionReportService.delete(zyInspectionReport);
//			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
//		}catch(Exception e){
//			e.printStackTrace();
//			message = "巡检报告删除失败";
//			throw new BusinessException(e.getMessage());
//		}
//		j.setMsg(message);
//		return j;
//	}
//	
//	/**
//	 * 批量删除巡检报告
//	 * 
//	 * @return
//	 */
//	 @RequestMapping(params = "doBatchDel")
//	@ResponseBody
//	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
//		AjaxJson j = new AjaxJson();
//		message = "巡检报告删除成功";
//		try{
//			for(String id:ids.split(",")){
//				ZyInspectionReportEntity zyInspectionReport = systemService.getEntity(ZyInspectionReportEntity.class, 
//				id
//				);
//				zyInspectionReportService.delete(zyInspectionReport);
//				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//			message = "巡检报告删除失败";
//			throw new BusinessException(e.getMessage());
//		}
//		j.setMsg(message);
//		return j;
//	}
	
	/**
	 * 巡检报告新增页面跳转
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(@RequestParam(value="planId",defaultValue="")String planId, HttpServletRequest req) {
		ZyInspectionPlanEntity zyInspectionPlan = systemService.get(ZyInspectionPlanEntity.class, planId);
		ZyInspectionPlanEntity zyIp = new ZyInspectionPlanEntity();
		String view = "";
		String type = "";
		try {
			/**
			 * 这里需要copy 一份ZyInspectionPlanEntity 
			 * 否则在对这个对面进行set操作时可能会被识别为更新操作
			 * 再次走service时会出现 引用未提交事务中的对象的异常
			 */
			MyBeanUtils.copyBean2Bean(zyIp, zyInspectionPlan);
			
//			String inspectionReportId = UUID.randomUUID().toString().replace("-", "");
//			req.setAttribute("inspectionReportId", inspectionReportId);
			//影院巡检联系人单查
			String cinemaId = zyIp.getEquipmentSpare().getZyCinema() != null ? zyIp.getEquipmentSpare().getZyCinema().getId() : "";
			ZyContactsEntity zyContact = zyInspectionPlanService.queryCinemaInspectionContact(cinemaId);
			zyIp.setContacter(zyContact);
			
			req.setAttribute("zyIP", zyIp);
			ZyInspectionReportEntity zyIr = systemService.findUniqueByProperty(ZyInspectionReportEntity.class, "inspectionPlanId", zyIp.getId());
			if(null == zyIr){
				zyIr = zyInspectionReportService.addReportFirst(planId);
			}else{
				List<Map<String, Object>> zyIrAttcInspectionImage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
				List<Map<String, Object>> zyIrAttcPackage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_DIAGNOSE_PACKAGE);
				List<Map<String, Object>> zyIrAttcCompletionImage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
				req.setAttribute("zyIrAttcInspectionImage", zyIrAttcInspectionImage);
				req.setAttribute("zyIrAttcPackage", zyIrAttcPackage);
				req.setAttribute("zyIrAttcCompletionImage", zyIrAttcCompletionImage);
			}
			
			req.setAttribute("zyInspectionR", zyIr);
			if(null != zyIp.getEquipmentSpare().getLaserReconstruction()
					&& zyIp.getEquipmentSpare().getLaserReconstruction().equals("1")){
				view = "com/zybk/zy_inspection_report/zyInspectionReport-jggz-add";//设备经过激光改造 光改
				type="激光改造";
			}else{
				if(null != zyIp.getEquipmentSpare().getType() && null != zyIp.getEquipmentSpare().getType().getEquipmentType()){//当前所属机型不为NULL，并且父节点不为NULL
					type=zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc();
					if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("RGB激光")){
						view = "com/zybk/zy_inspection_report/zyInspectionReport-RGB-add";//三级分类为RGB激光
					}else if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("荧光粉激光")
							 || zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("X系列")){
						view = "com/zybk/zy_inspection_report/zyInspectionReport-ygf-add";//三级分类为荧光粉激光 Lp
					}else if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("E系列")){
						view = "com/zybk/zy_inspection_report/zyInspectionReport-E-add";//三级分类为E系列
					}else{
						view = "com/zybk/zy_inspection_report/zyInspectionReport-other-add";//其他机型 s,c,b
					}
				}else{
					view = "com/zybk/zy_inspection_report/zyInspectionReport-other-add";//其他机型
				}
			}
			req.setAttribute("engItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "ENG"));
			req.setAttribute("TIICPItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "TI/ICP"));
			req.setAttribute("LPSItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "LPS"));
			req.setAttribute("LDMItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "LDM"));
			req.setAttribute("EnigmaItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "Enigma"));
			req.setAttribute("ControlerItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "Controller"));
			req.setAttribute("SMPSItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "SMPS"));
			req.setAttribute("touchItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "触摸屏"));
			req.setAttribute( "type",type );//机型



			System.err.println(view.substring(view.lastIndexOf("/")+1));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView(view);
	}
	
	
	/**
	 * 添加巡检报告
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyInspectionReportEntity zyInspectionReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "巡检报告提交成功";
		try{
			//saveType 标示的是 操作人的类型 ； 1 是在zyIr-* 里操作的
			String saveType = oConvertUtils.getString(request.getParameter("saveType"));
			//saveMode 标示的是 保存的类型 1 是暂存，2是保存
			String saveMode = oConvertUtils.getString(request.getParameter("saveMode"));
			String appSave = oConvertUtils.getString(request.getParameter("appSave"));
			/**这里的对象存储，如果页面不选择值，应该做判断处理 -- begin*/
			zyInspectionReport.setTmsBrand((null != zyInspectionReport.getTmsBrand() && zyInspectionReport.getTmsBrand().getId().equals("")) ? null : zyInspectionReport.getTmsBrand());
			zyInspectionReport.setServerBrand((null != zyInspectionReport.getServerBrand() && zyInspectionReport.getServerBrand().getId().equals("")) ? null : zyInspectionReport.getServerBrand());
			/**这里的对象存储，如果页面不选择值，应该做判断处理 -- end  */
			String IRId = zyInspectionReport.getId();
			ZyInspectionReportEntity zyIr = zyInspectionReportService.get(ZyInspectionReportEntity.class, IRId);//用作更新用
			String inspectionPlanId = zyInspectionReport.getInspectionPlanId();
			//如果用巡检报告ID 没有查询到巡检报告。那么用巡检计划ID查询。防止在APP填写巡检报告时发生了一些不可思议的事情
			if(null == zyIr){
				//防止这里多个巡检报告问题不是出现在这里
				List<ZyInspectionReportEntity> irs = zyInspectionReportService.findHql("from ZyInspectionReportEntity where inspectionPlanId=? order by createDate DESC ", inspectionPlanId);
				if(null != irs && irs.size() > 0){
					zyIr = irs.get(0);
				}
			}
			if(null == zyIr){
				//第一次 暂存,或保存的时候 初始化值
				zyInspectionReport.setIsChecked(false);
				//并且创建巡检报告
				zyInspectionReportService.save(zyInspectionReport);
			}else{
				if(appSave.equals("1")){//APP 中暂存的时候不覆盖原有的数据(因为APP未能显示所有PC端的字段。所以覆盖复制会覆盖掉一部分数据)
					MyBeanUtils.copyBeanNotNull2Bean(zyInspectionReport, zyIr);
				}else{
					BeanUtils.copyProperties(zyIr,zyInspectionReport);
				}
				zyInspectionReportService.saveOrUpdate(zyIr);
			}
			
			ZyInspectionReportEntity zyCompareIr = zyInspectionReportService.get(ZyInspectionReportEntity.class, IRId);//留做比对修改记录用
			if(saveType.equals("1") && null != zyCompareIr){
				message = "巡检报告修改成功";
				zyInspectionReportService.compareReport(zyInspectionReport,zyCompareIr,request);
			}
			//1 是暂存，2是保存
			if(saveMode.equals("2") && !saveType.equals("1")){//是保存的 并且不是 在 zyIr里操作的
				zyInspectionReportService.updateIpAndSavePlanRecord(zyInspectionReport);
				cbsInspectionEvaluateServiceI.createInspectionEvaluate(zyInspectionReport.getInspectionPlanId());
			}else if(saveMode.equals("1")){
				message = "巡检报告暂存成功";
			}
			//暂存或保存 都保存附件
			String[] attInspectionImageArr = request.getParameterValues(StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
			String[] attDiagonsePackageArr = request.getParameterValues(StaticValue.DIC_REPORT_ATTACH_TYPE_DIAGNOSE_PACKAGE);
			String[] attCompletionImageArr = request.getParameterValues(StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
			zyInspectionReportService.saveAttachment(IRId, attInspectionImageArr,StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
			zyInspectionReportService.saveAttachment(IRId, attDiagonsePackageArr,StaticValue.DIC_REPORT_ATTACH_TYPE_DIAGNOSE_PACKAGE);
			zyInspectionReportService.saveAttachment(IRId, attCompletionImageArr,StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "巡检报告添加失败";
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-7-27 下午3:29:10
	 * Description 接收 上传巡检报告附件的文件流
	 */
	@ResponseBody
	@RequestMapping(params="uploadIrAttachment")
	public void uploadIrAttachment(HttpServletRequest request){
		zyInspectionReportService.uploadIrAttachment(request);
	}
	
	/**
	 * @author xiul
	 * 2016-5-17 下午2:06:07
	 * Description 查看巡检报告 或者 修改巡检报告 
	 */
	@RequestMapping(params="goViewOrUpateIr")
	public ModelAndView goViewOrUpateIr(HttpServletRequest req){
		String zyIpId = req.getParameter("zyIpId");
		String operationType = req.getParameter("operationType");
		req.setAttribute("operationType", operationType);
		String view = "";
		String type = "";
		try {
			//获取角色
			TSUser user = ResourceUtil.getSessionUserName();
			List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
			List<String> todoRoles = new ArrayList<String>();
			List<String> remindRoles = new ArrayList<String>();
			List<String> userRoleCodeList = new ArrayList<String>();
			for (TSRoleUser tsRoleUser : roleUsers) {
				userRoleCodeList.add(tsRoleUser.getTSRole().getRoleCode());
			}
			if(userRoleCodeList.contains(StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR)){ //巴可服务商
				req.setAttribute("BK", "BK");
			}


			ZyInspectionPlanEntity zyInspectionPlan = systemService.get(ZyInspectionPlanEntity.class, zyIpId);
			ZyInspectionPlanEntity zyIp = new ZyInspectionPlanEntity();
			/**
			 * 这里需要copy 一份ZyInspectionPlanEntity 
			 * 否则在对这个对面进行set操作时可能会被识别为更新操作
			 * 再次走service时会出现 引用未提交事务中的对象的异常
			 */
			MyBeanUtils.copyBean2Bean(zyIp, zyInspectionPlan);
			//影院巡检联系人单查
			String cinemaId = zyIp.getEquipmentSpare().getZyCinema() != null ? zyIp.getEquipmentSpare().getZyCinema().getId() : "";
			ZyContactsEntity zyContact = zyInspectionPlanService.queryCinemaInspectionContact(cinemaId);
			zyIp.setContacter(zyContact);
			
			String inspectionReportId = UUID.randomUUID().toString().replace("-", "");
			req.setAttribute("inspectionReportId", inspectionReportId);
			req.setAttribute("zyIP", zyIp);
			ZyInspectionReportEntity zyIr = systemService.findUniqueByProperty(ZyInspectionReportEntity.class, "inspectionPlanId", zyIp.getId());
			if(null == zyIr){
				zyIr = zyInspectionReportService.addReportFirst(zyIpId);
			}else{
				List<Map<String, Object>> zyIrAttcInspectionImage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
				List<Map<String, Object>> zyIrAttcPackage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_DIAGNOSE_PACKAGE);
				List<Map<String, Object>> zyIrAttcCompletionImage = zyInspectionReportService.findReportAttachment(zyIr.getId(),StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
				req.setAttribute("zyIrAttcInspectionImage", zyIrAttcInspectionImage);
				req.setAttribute("zyIrAttcPackage", zyIrAttcPackage);
				req.setAttribute("zyIrAttcCompletionImage", zyIrAttcCompletionImage);
			}
			
			req.setAttribute("zyInspectionR", zyIr);
			if(null != zyIp.getEquipmentSpare().getLaserReconstruction()
					&& zyIp.getEquipmentSpare().getLaserReconstruction().equals("1")){
				type="激光改造";
				view = "com/zybk/zy_inspection_report/zyIr-jggz";//设备经过激光改造
			}else{
				type=zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc();
				if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("RGB激光")){
					view = "com/zybk/zy_inspection_report/zyIr-RGB";//三级分类为RGB激光
				}else if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("荧光粉激光") || zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("X系列")){
					view = "com/zybk/zy_inspection_report/zyIr-ygf";//三级分类为荧光粉激光
				}else if(zyIp.getEquipmentSpare().getType().getEquipmentType().getTypeDesc().equals("E系列")){
					view = "com/zybk/zy_inspection_report/zyIr-E";//三级分类为E系列
				}else{
					view = "com/zybk/zy_inspection_report/zyIr-other";//其他机型
				}
			}

			req.setAttribute( "type",type );//机型
			req.setAttribute("engItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "ENG"));
			req.setAttribute("TIICPItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "TI/ICP"));
			req.setAttribute("LPSItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "LPS"));
			req.setAttribute("LDMItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "LDM"));
			req.setAttribute("EnigmaItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "Enigma"));
			req.setAttribute("ControlerItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "Controller"));
			req.setAttribute("SMPSItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "SMPS"));
			req.setAttribute("touchItemList", systemService.findHql("FROM ZyEsItemEntity WHERE type.typeDesc = ?", "触摸屏"));
			System.err.println(view.substring(view.lastIndexOf("/")+1));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView(view);
	}
	
	/**
	 * @author xiul
	 * 2017-3-9 上午11:44:03
	 * Description APP在点击 上传报告 时检验是否已经在PC端打开过 填写报告 页面
	 * @return 是：已经存在的巡检报告ID 否：null
	 */
	@ResponseBody
	@RequestMapping(params="queryDidIpHadIr")
	public AjaxJson queryDidIpHadIr(HttpServletRequest req){
		AjaxJson aj = new AjaxJson();
		try {
			String ipId = req.getParameter("ipId");
			if(!StringUtil.isEmpty(ipId)){
				ZyInspectionReportEntity zyIr = systemService.findUniqueByProperty(ZyInspectionReportEntity.class, "inspectionPlanId", ipId);
				if(zyIr == null){
					zyIr = zyInspectionReportService.addReportFirst(ipId);
				}
				aj.setObj(zyIr);
			}else{
				aj.setSuccess(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			aj.setSuccess(false);
		}
		return aj;
	}
	
	
	/**
	 * @author xiul
	 * 2016-5-5 下午7:19:14
	 * Description 删除巡检报告 附件 （不同于普通删除附件） 
	 * @param inspectionPlanId
	 * @param fileBeanId
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params="deleteAttachment")
	public AjaxJson deleteAttachment(
			@RequestParam(value="irId",defaultValue="")String irId,
			@RequestParam(value="fileBeanId",defaultValue="")String fileBeanId,
			@RequestParam(value="type",defaultValue="")String type){
		AjaxJson j = new AjaxJson();
		try {
			zyInspectionReportService.deleteAttach(irId,fileBeanId,type);
		} catch (Exception e) {
			j.setMsg("删除附件失败");
			j.setSuccess(false);
			e.printStackTrace();
		}
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-5-5 下午8:05:32
	 * Description 巡检问题分析报表页 
	 * @return
	 */
	@RequestMapping(params="goZyInspectionProblemAnalysisReport")
	public ModelAndView goZyInspectionProblemAnalysisReport(HttpServletRequest req){
		List<String> years = zyCommonService.queryYearsInIp();
		req.setAttribute("years", years);
		return new ModelAndView("com/zybk/zy_inspection_report/zyInspectionProblemAnalysisReport");
	}
	
	/**
	 * @author xiul
	 * 2016-5-5 下午8:05:46
	 * Description 巡检问题分析报表页 - 列表数据
	 * @param year 年份
	 * @param departIds 机构ids
	 */
	@ResponseBody
	@RequestMapping(params="getIpProblemReportData")
	public AjaxJson getIpProblemReportData(HttpServletRequest req,
			@RequestParam(value="year")String year,
			@RequestParam(value="esTypes",defaultValue="")String esTypes,
			@RequestParam(value="departIds",defaultValue="")String departIds){
		AjaxJson j = new AjaxJson();
		try {
			List<Map<String,Object>> temperatureExs = zyInspectionReportService.getIpProblemReportData("is_temperature_ex", "1", year,departIds, esTypes);
			List<Map<String,Object>> humidityExs = zyInspectionReportService.getIpProblemReportData("is_humidity_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> coolantPressureExs = zyInspectionReportService.getIpProblemReportData("is_coolant_pressure_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> coolantHeightExs = zyInspectionReportService.getIpProblemReportData("is_coolant_height_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> brightnessExs = zyInspectionReportService.getIpProblemReportData("is_brightness_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> windSpeedExs = zyInspectionReportService.getIpProblemReportData("is_wind_speed_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> zeroGroundVoltageExs = zyInspectionReportService.getIpProblemReportData("is_zero_ground_voltage_ex","1", year, departIds, esTypes);
			List<Map<String,Object>> trainingNumExs = zyInspectionReportService.getIpProblemReportData("is_training_num_ex","1", year, departIds, esTypes);
			
			Map<String, Object> totalPlansByMonth = zyInspectionReportService.getTotalPlansByMonth(year, departIds, esTypes);
			List<Map<String,Object>> ipExInMonth = zyInspectionReportService.getIpProblemReportData(null,null,year,departIds,esTypes);
			j.setAttributes(totalPlansByMonth);
			Map<String, Object> reMap = new HashMap<String, Object>();
			reMap.put("temperatureExs", temperatureExs);
			reMap.put("humidityExs", humidityExs);
			reMap.put("coolantPressureExs", coolantPressureExs);
			reMap.put("coolantHeightExs", coolantHeightExs);
			reMap.put("brightnessExs", brightnessExs);
			reMap.put("windSpeedExs", windSpeedExs);
			reMap.put("zeroGroundVoltageExs", zeroGroundVoltageExs);
			reMap.put("trainingNumExs", trainingNumExs);
			reMap.put("ipExInMonth", ipExInMonth);
			reMap.put("departIds", departIds);
			reMap.put("esTypes", esTypes);
			j.setObj(reMap);
		} catch (Exception e) {
			j.setMsg("查询数据异常");
			j.setSuccess(false);
			e.printStackTrace();
		}
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-9-19 下午3:39:30
	 * Description 巡检问题分析报表 - 按区域汇总tab页数据 
	 */
	@ResponseBody
	@RequestMapping(params="getIrTtTableData")
	public AjaxJson getIrTtTableData(
			@RequestParam(value="year")String year,
			@RequestParam(value="departIds",defaultValue="")String departIds,
			@RequestParam(value="irExType",defaultValue="")String irExType,
			@RequestParam(value="ttIds",defaultValue="")String ttIds){
		AjaxJson j = new AjaxJson();
		List<Map<String,Object>> irExsGroupByTerritory = zyInspectionReportService.getIpProblemReportDataGroupByTerritory(year,departIds,irExType,ttIds);
		j.setObj(irExsGroupByTerritory);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2017-5-11 上午10:14:33
	 * Description 巡检问题分析报表 - 各省问题汇总 - 堆叠柱状图 ，地图
	 */
	@ResponseBody
	@RequestMapping(params="queryEachCityPillarData")
	public List<JSONObject> queryEachCityPillarData(
			@RequestParam(value="year")String year,
			@RequestParam(value="departIds",defaultValue="")String departIds,
			@RequestParam(value="irExType",defaultValue="")String irExType,
			@RequestParam(value="ttIds",defaultValue="")String ttIds){
		return zyInspectionReportService.queryEachCityPillarData(year,departIds,irExType,ttIds);
	}
	
	/**
	 * @author xiul
	 * 2016-12-7 下午4:51:13
	 * Description 返回机型 tree
	 */
	@ResponseBody
	@RequestMapping(params="getEsTypesTreeForIrReport")
	public List<ComboTree> getEsTypesTreeForIrReport(){
		return zyInspectionReportService.getEsTypesTreeForIrReport();
	}
 	
	/**
	 * @author xiul
	 * 2016-5-6 下午4:07:36
	 * Description 跳转 弹出选择机构页 
	 * @return
	 */
	@RequestMapping(params="goChooseOrgsForIrReport")
	public ModelAndView goChooseOrgsForIrReport(){
		return new ModelAndView("com/zybk/zy_inspection_report/zyChooseOrgForIrProblem");
	}
	
	/**
	 * @author xiul
	 * 2016-5-6 下午4:10:51
	 * Description 弹出选择机构页 datagrid  
	 */
	@ResponseBody
	@RequestMapping(params = "chooseOrgDatagrid")
	public void chooseOrgDatagrid(TSDepart tsDepart,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tsDepart, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * @author xiul
	 * 2017-5-11 下午6:25:10
 	 * Description 弹出选择省份页面 跳转 - 巡检问题分析报告
	 */
	@RequestMapping(params="goChooseTTForIrReport")
	public ModelAndView goChooseTTForIrReport(){
		return new ModelAndView("com/zybk/zy_inspection_report/zyChooseTTForIrProblem");
	}
	
	/**
	 * @author xiul
	 * 2016-5-6 下午4:10:51
	 * Description 弹出选择省份页面datagrid - 巡检问题分析报告
	 */
	@ResponseBody
	@RequestMapping(params = "chooseTtDatagrid")
	public void chooseTtDatagrid(TSTerritory territory,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSTerritory.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, territory, request.getParameterMap());
		try{
		//自定义追加查询条件
			cq.add(Restrictions.eq("territoryLevel", (short)1));
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	
	
	/**
	 * @author xiul
	 * 2016-5-6 下午4:07:36
	 * Description 跳转 弹出选择机型列表 - 巡检问题报告页用
	 * @return
	 */
	@RequestMapping(params="goChooseEsTypeForIrReport")
	public ModelAndView goChooseEsTypeForIrReport(){
		return new ModelAndView("com/zybk/zy_inspection_report/zyChooseEsTypeForIrProblem");
	}
	
	/**
	 * @author xiul
	 * 2016-5-6 下午4:10:51
	 * Description 弹出选择机型页 datagrid
	 */
	@ResponseBody
	@RequestMapping(params = "chooseEsTypeDatagrid")
	public List<TreeGrid> chooseEsTypeDatagrid(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.eq("typeDesc","放映机");//amy 3852 BUG只查询放映机下的
		}
		cq.add();
		List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType.id");
		treeGridModel.setParentText("equipmentType.typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}
	
	/**
	 * @author xiul
	 * 2016-5-10 下午1:55:03
	 * Description 巡检实时报表 
	 * @return
	 */
	@RequestMapping(params="zyIpRealTimeReport")
	public ModelAndView zyIpRealTimeReport(HttpServletRequest req){
		List<String> years = zyCommonService.queryYearsInIp();
		req.setAttribute("years", years);
		TSUser user = ResourceUtil.getSessionUserName();
		if(userService.hasRoles(user.getUserName(), new String[]{StaticValue.RULE_CODE_THIRDPARTY_HEADER,StaticValue.RULE_CODE_THIRDPARTY_MANAGER})){
			req.setAttribute("tpRoleUser", true);
			req.setAttribute("userDpId", user.getCurrentDepart().getId());
			req.setAttribute("userDpCode", user.getCurrentDepart().getOrgCode());
		}
		return new ModelAndView("com/zybk/zy_inspection_report/zyIpRealTimeReport");
	}
	/**
	 * @author xiul
	 * 2016-5-10 下午2:47:52
	 * Description 查询 巡检实时报表 数据 
	 * @param company 巡检单位code
	 * @param year 年份
	 * @param type 月报 ，周报
	 */
	@ResponseBody
	@RequestMapping(params="queryIpRealTimeReportData")
	public JSONObject queryIpReportData(
			@RequestParam(value="company",defaultValue="")String company,
			@RequestParam(value="year")String year,
			@RequestParam(value="type")String type,
			@RequestParam(value="egIds",required=false)String egIds
			){
		TSUser user = ResourceUtil.getSessionUserName();
		boolean tpRoleUser = userService.hasRoles(user.getUserName(), new String[]{StaticValue.RULE_CODE_THIRDPARTY_HEADER,StaticValue.RULE_CODE_THIRDPARTY_MANAGER});
		JSONObject json = new JSONObject();
		List<Highchart> highCharts= zyInspectionReportService.queryIpReportData(company, year, type, egIds);
		json.accumulate("highCharts", highCharts);//折线图
		List<Highchart> highChartsDuiDie = zyInspectionReportService.queryIpProgressReportDataDuiDie(tpRoleUser, year, company,egIds);
		json.accumulate("highChartsDuiDie", highChartsDuiDie);//堆叠柱状图
		return json;
	}
	
	/**
	 * @author xiul
	 * 2016-5-10 下午1:55:03
	 * Description 巡检进度报表 
	 * @return
	 */
	@RequestMapping(params="zyIpProgressReport")
	public ModelAndView zyIpProgressReport(HttpServletRequest req){
		List<String> years = zyCommonService.queryYearsInIp();
		req.setAttribute("years", years);
		TSUser user = ResourceUtil.getSessionUserName();
		if(userService.hasRoles(user.getUserName(), new String[]{StaticValue.RULE_CODE_THIRDPARTY_HEADER,StaticValue.RULE_CODE_THIRDPARTY_MANAGER})){
			req.setAttribute("tpRoleUser", true);
			req.setAttribute("userDpId", user.getCurrentDepart().getId());
		}
		return new ModelAndView("com/zybk/zy_inspection_report/zyIpProgressReport");
	}
	
	/**
	 * @author xiul
	 * 2016-5-11 下午1:59:36
	 * Description 查询 巡检进度报表数据
	 */
	@ResponseBody
	@RequestMapping
	public JSONObject queryIpProgressReportData(
			@RequestParam(value="year")String year,
			@RequestParam(value="departIds",defaultValue="")String departIds
			){
		TSUser user = ResourceUtil.getSessionUserName();
		boolean tpRoleUser = userService.hasRoles(user.getUserName(), new String[]{StaticValue.RULE_CODE_THIRDPARTY_HEADER,StaticValue.RULE_CODE_THIRDPARTY_MANAGER});
		JSONObject json = new JSONObject();
		List<Highchart> highCharts = zyInspectionReportService.queryIpProgressReportData(year, departIds);
		json.accumulate("highCharts", highCharts);//table + 折线图
		

		return json;
	}
	
	/**
	 * @author xiul
	 * 2016-5-17 下午5:46:20
	 * Description 报表页 - 导出报告 
	 * @param fileName 文件名称
	 * @param tableData table数据
	 */
	@RequestMapping(params="exportIrReport")
	public void exportIrReport(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="fileName",defaultValue="文件")String fileName,
			@RequestParam(value="tableData",defaultValue="")String tableData,
		   @RequestParam(value="ipCompany",defaultValue="")String ipCompany){
		zyInspectionReportService.exportIrReport(fileName,tableData,ipCompany,response);
	}
	
//	/**
//	 * @author xiul
//	 * 2016-8-22 上午11:37:03
//	 * Description APP - 工程师保存巡检报告 
//	 */
//	@ResponseBody
//	@RequestMapping(params="appAddReport")
//	public AjaxJson appAddReport(HttpServletRequest request,ZyInspectionReportEntity zyIr){
//		AjaxJson j = new AjaxJson();
//		try {
//			PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(zyIr);
//			for (PropertyDescriptor pd : descriptors) {
//				String name = pd.getName();
//				System.out.println(name + "<>" + PropertyUtils.getSimpleProperty(zyIr, name));
//			}
//			
//			String[] attInspectionImageArr = request.getParameterValues(StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
//			String[] attCompletionImageArr = request.getParameterValues(StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
//			for (String str : attInspectionImageArr) {
//				System.out.println("巡检图片"+str);
//			}
//			for (String str : attCompletionImageArr) {
//				System.out.println("完工单"+str);
//			}
////			zyInspectionReportService.saveAttachment(zyIr.getId(), attInspectionImageArr,StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE);
////			zyInspectionReportService.saveAttachment(zyIr.getId(), attCompletionImageArr,StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE);
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return j;
//	}
	
	
	
//	/**
//	 * 更新巡检报告
//	 * 
//	 * @param ids
//	 * @return
//	 */
//	@RequestMapping(params = "doUpdate")
//	@ResponseBody
//	public AjaxJson doUpdate(ZyInspectionReportEntity zyInspectionReport, HttpServletRequest request) {
//		AjaxJson j = new AjaxJson();
//		message = "巡检报告更新成功";
//		ZyInspectionReportEntity t = zyInspectionReportService.get(ZyInspectionReportEntity.class, zyInspectionReport.getId());
//		try {
//			MyBeanUtils.copyBeanNotNull2Bean(zyInspectionReport, t);
//			zyInspectionReportService.saveOrUpdate(t);
//			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
//		} catch (Exception e) {
//			e.printStackTrace();
//			message = "巡检报告更新失败";
//			throw new BusinessException(e.getMessage());
//		}
//		j.setMsg(message);
//		return j;
//	}
	


	
//	/**
//	 * 巡检报告编辑页面跳转
//	 * 
//	 * @return
//	 */
//	@RequestMapping(params = "goUpdate")
//	public ModelAndView goUpdate(ZyInspectionReportEntity zyInspectionReport, HttpServletRequest req) {
//		if (StringUtil.isNotEmpty(zyInspectionReport.getId())) {
//			zyInspectionReport = zyInspectionReportService.getEntity(ZyInspectionReportEntity.class, zyInspectionReport.getId());
//			req.setAttribute("zyInspectionReportPage", zyInspectionReport);
//		}
//		return new ModelAndView("com/zybk/zy_inspection_report/zyInspectionReport-update");
//	}
//	
//	/**
//	 * 导入功能跳转
//	 * 
//	 * @return
//	 */
//	@RequestMapping(params = "upload")
//	public ModelAndView upload(HttpServletRequest req) {
//		return new ModelAndView("com/zybk/zy_inspection_report/zyInspectionReportUpload");
//	}
//	
//	/**
//	 * 导出excel
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(params = "exportXls")
//	public String exportXls(ZyInspectionReportEntity zyInspectionReport,HttpServletRequest request,HttpServletResponse response
//			, DataGrid dataGrid,ModelMap modelMap) {
//		CriteriaQuery cq = new CriteriaQuery(ZyInspectionReportEntity.class, dataGrid);
//		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyInspectionReport, request.getParameterMap());
//		List<ZyInspectionReportEntity> zyInspectionReports = this.zyInspectionReportService.getListByCriteriaQuery(cq,false);
//		modelMap.put(NormalExcelConstants.FILE_NAME,"巡检报告");
//		modelMap.put(NormalExcelConstants.CLASS,ZyInspectionReportEntity.class);
//		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("巡检报告列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
//			"导出信息"));
//		modelMap.put(NormalExcelConstants.DATA_LIST,zyInspectionReports);
//		return NormalExcelConstants.JEECG_EXCEL_VIEW;
//	}
//	/**
//	 * 导出excel 使模板
//	 * 
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(params = "exportXlsByT")
//	public String exportXlsByT(ZyInspectionReportEntity zyInspectionReport,HttpServletRequest request,HttpServletResponse response
//			, DataGrid dataGrid,ModelMap modelMap) {
//		modelMap.put(TemplateExcelConstants.FILE_NAME, "巡检报告");
//		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
//		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
//		modelMap.put(TemplateExcelConstants.CLASS,ZyInspectionReportEntity.class);
//		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
//		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
//	}
//	
//	@SuppressWarnings("unchecked")
//	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
//	@ResponseBody
//	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
//		AjaxJson j = new AjaxJson();
//		
//		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//			MultipartFile file = entity.getValue();// 获取上传文件对象
//			ImportParams params = new ImportParams();
//			params.setTitleRows(2);
//			params.setHeadRows(1);
//			params.setNeedSave(true);
//			try {
//				List<ZyInspectionReportEntity> listZyInspectionReportEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),ZyInspectionReportEntity.class,params);
//				for (ZyInspectionReportEntity zyInspectionReport : listZyInspectionReportEntitys) {
//					zyInspectionReportService.save(zyInspectionReport);
//				}
//				j.setMsg("文件导入成功！");
//			} catch (Exception e) {
//				j.setMsg("文件导入失败！");
//				logger.error(ExceptionUtil.getExceptionMessage(e));
//			}finally{
//				try {
//					file.getInputStream().close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//		return j;
//	}
}

